#include <Arduino.h> 
#include <string.h>
#include <HTTPClient.h>
#include <sstream>
#include <iostream>   
#include <driver/gpio.h>
#include "../lib/ArduinoJson/ArduinoJson.h"
#include "front.h"
#include "12864.h"
#include "RC522.h"
#include "WiFiUtils.h"
#include "EMQX.h"
#include "utils.h"

void setup() {
  Serial.begin(115200);
  Serial.println("2222");
  init_wifi();
  /** 初始化屏幕 **/
  init_12864();
  /**初始化RC522*/
  init_RC522();
  /**初始化EMQX*/
  initEMQX();
  pinMode(LED, OUTPUT);
}

void loop() {
  if (!isRC522Using) {
    client.loop();
  }
  if (!mfrc522.PICC_IsNewCardPresent() || isEMQXUsing) { // 发现不是新卡的进入
    display.clearDisplay();
    display.setTextColor(WHITE);// 开像素点发光,白色字体
    display.setTextSize(2);
    display.drawBitmap(0, 0, str1[0], 16, 16, 1); //状
    display.drawBitmap(16, 0, str1[1], 16, 16, 1); //态
    display.setCursor(32, 0);
    display.print(":");
    if (isUsing) {
      display.drawBitmap(48, 0, str1[2], 16, 16, 1); //*"使",2*/
      display.drawBitmap(64, 0, str1[3], 16, 16, 1); //*"用",3*/
      display.drawBitmap(80, 0, str1[4], 16, 16, 1); //*"中",4*/
    }
    else {
      display.drawBitmap(48, 0, str1[5], 16, 16, 1); //*"空",5*/
      display.drawBitmap(64, 0, str1[6], 16, 16, 1); //*"闲",6*/
    }
    struct tm time1;
    if (isUsing) {
      if (userBalance <= 0) {  // 余额不足时停止使用
        stopUsing(userCardId, usedTime);
        isUsing = false;
        isRC522Using = false;
        client.publish(publishTopic, "{\"status\":\"stop\"}");
      }
      else {
        if (!getLocalTime(&time1)) {
          display.println("Failed to obtain time");
          return;
        }
        usedTime = difftime(mktime(&time1), mktime(&time0));
        display.drawBitmap(0, 18, str1[7], 16, 16, 1); //消
        display.drawBitmap(16, 18, str1[8], 16, 16, 1); //费
        display.setCursor(32, 18);
        display.print(":");
        display.print(String(usedTime * pricePerSecond));
        display.drawBitmap(0, 34, str1[9], 16, 16, 1); //余
        display.drawBitmap(16, 34, str1[10], 16, 16, 1); //额
        display.setCursor(32, 34);
        display.print(":");
        display.println(String(userBalance - usedTime * pricePerSecond));
      }
    }
    display.display();
    return;
  }
  if (!mfrc522.PICC_ReadCardSerial()) {    //选择一张卡      
    return;
  }
  Serial.print("发现一张卡:");
  userCardId = arrayToString(mfrc522.uid.uidByte, mfrc522.uid.size);//获取卡的id字符串String 
  Serial.println(userCardId);
  if (isUsing) {
    isUsing = false;
    isRC522Using = false;
    digitalWrite(LED, LOW);
    stopUsing(userCardId, usedTime);
    client.publish(publishTopic, "{\"status\":\"stop\"}");
  }
  else {
    //调用API接口获取卡余额
    String api = API + "user/getUserBalanceByUserCardId?userCardId=" + userCardId;
    HTTPClient http;
    http.begin(api); //HTTP begin
    int httpCode = http.GET();
    if (httpCode > 0) {
      Serial.printf("HTTP Get Code: %d\r\n", httpCode);
      if (httpCode == HTTP_CODE_OK) { // 收到正确的内容
        String resBuff = http.getString();
        //	输出示例：{"mid":123456789,"following":226,"whisper":0,"black":0,"follower":867}}
        //	输出示例：{"code":"200","userBalance":80.48}
        Serial.println(resBuff);
        deserializeJson(doc, resBuff); //开始使用Json解析
        if (doc["code"] == "200") {
          //获取开始取水的时间戳,开始计时
          if (!getLocalTime(&time0)) {
            display.println("Failed to obtain time");
            return;
          }
          digitalWrite(LED, HIGH);
          userBalance = doc["userBalance"];
          Serial.println(userCardId + "'s balance:" + userBalance);
          pricePerSecond = doc["pricePerSecond"];
          isUsing = true;
          isRC522Using = true;
          client.publish(publishTopic, "{\"status\":\"using\"}");
        }
        else {
          return;
        }
      }
    }
    else {
      Serial.printf("HTTP Get Error: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
  }
  mfrc522.PICC_HaltA();    // Stop encryption on PCD    
  mfrc522.PCD_StopCrypto1();
}


